﻿scene.mesh = (function ($, undefined)
{
    var _renderFunctions = null;
    var _meshes = [];

    var init = function (renderFunctions)
    {
        _renderFunctions = renderFunctions;
        
        $("#shuffle_button").click(function () {
            _shuffleObjects(_meshes);
        });
    };
    
    var destroy = function ()
    {
        _meshes = null;
    };

    var addMeshesToScene = function (scene, actualDistances)
    {
        _meshes = [];

        // Create an object for each mutualDistance entry
        $.each(actualDistances, function (i, mutualDistances) {
            var position = new THREE.Vector3(
                (Math.random() - 0.5),
                (Math.random() - 0.5),
                (Math.random() - 0.5));

            var material = new THREE.MeshPhongMaterial({
                color: 0x00ff00,
                shininess: 300,
                shading: THREE.SmoothShading
            });

            var mesh = _createSphere(position, material);
            mesh.geometry.dynamic = true;
            
            mesh.identifier = mutualDistances.EntityId;
            mesh.velocity = new THREE.Vector3(0, 0, 0);

            scene.add(mesh);
            _meshes.push(mesh);
        });

        return _meshes;
    };

    var removeMeshesFromScene = function(scene)
    {
        $.each(_meshes, function (i, mesh) {
            scene.remove(mesh);
        });
    };

    var _shuffleObjects = function (meshes) {
        $.each(meshes, function (i, mesh) {
            var position = new THREE.Vector3(
                (Math.random() - 0.5),
                (Math.random() - 0.5),
                (Math.random() - 0.5));

            mesh.position = position;
        });
    };

    var _createSphere = function (position, material)
    {
        var radius = 1,
            segmentsWidth = 30,
            segmentsHeight = 20;

        // Create a sphere
        var sphereGeometry = new THREE.SphereGeometry(radius, segmentsWidth, segmentsHeight);
        var mesh = new THREE.Mesh(sphereGeometry, material);

        mesh.position = position;

        return mesh;
    };

    var _createCube = function (position, material)
    {
        // Create a Cube
        var cubeGeometry = new THREE.CubeGeometry(1, 1, 1);
        var mesh = new THREE.Mesh(cubeGeometry, material);

        mesh.position = position;
        _renderFunctions.push(function () {
            mesh.rotation.x += 0.02;
            mesh.rotation.y += 0.01;
        });

        return mesh;
    };

    // public API
    return {
        init: init,
        destroy: destroy,
        addMeshesToScene: addMeshesToScene,
        removeMeshesFromScene: removeMeshesFromScene
    };
})(jQuery);